package com.hanson.common.Interceptor;

import com.hanson.Const;
import com.hanson.common.bean.WeiXinConfig;
import com.hanson.common.service.RedisService;
import com.hanson.common.util.BusinessUtil;
import com.hanson.entity.UserBean;
import com.hanson.service.UserService;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.api.WxConsts;
import me.chanjar.weixin.mp.api.WxMpService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.net.URLEncoder;

@Slf4j
@Component
public class LoginInterceptor implements HandlerInterceptor {

    private static final String[] IGNORE_URI = {"/js/", ".js", ".css", ".jpg", ".ttf", ".woff",
            "woff2", ".txt", ".gif", ".png", "/error", ".PNG", ".GIF", ".JPG", ".xls", ".xlsx", ".swf", "favicon.ico",
            "/admin/login", "/admin/logout",
//            "/web/index", "/web/category", "/web/skillGoods", "/web/groupGoods", "/web/search", "/web/searchResult",
//            "/web/searchType", "/web/hotMore", "/web/benefitMore", "/web/bestMore",
            "/weixin"};

    @Autowired
    private RedisService redisService;
    @Autowired
    private WxMpService wxMpService;
    @Autowired
    private UserService userService;
    @Autowired
    private WeiXinConfig weiXinConfig;

    /**
     * 预处理回调方法，实现处理器的预处理
     * 返回值：true表示继续流程；false表示流程中断，不会继续调用其他的拦截器或处理器
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
        String requestUri = request.getRequestURI();
        for (String s : IGNORE_URI) {
            if (requestUri.contains(s)) {
                return true;
            }
        }
        if (requestUri.contains("/web/")) {
            if (requestUri.equals("/web/userCenter")) {
                String param = request.getParameter("parentId");
                if (StringUtils.isNotEmpty(param)) {
                    requestUri += "?parentId=" + param;
                }
            }
            String openId = BusinessUtil.getCookieToken(request, "openId");
            if (StringUtils.isEmpty(openId)) {
                log.info("requestUri:{} openID为空 获取用户信息", requestUri);
                String authUrl = weiXinConfig.getDomian() + "weixin/auth";
                String redirectURL = wxMpService.oauth2buildAuthorizationUrl(authUrl, WxConsts.OAuth2Scope.SNSAPI_USERINFO, requestUri);
                response.sendRedirect(redirectURL);
                return false;
            } else {
                UserBean userBean = userService.selectByOpenId(openId);
                //当前用户不存在了
                if (null == userBean) {
                    log.info("requestUri:{} openID{}查询不到用户 获取用户信息", openId, requestUri);
                    String authUrl = weiXinConfig.getDomian() + "weixin/auth";
                    String redirectURL = wxMpService.oauth2buildAuthorizationUrl(authUrl, WxConsts.OAuth2Scope.SNSAPI_USERINFO, requestUri);
                    response.sendRedirect(redirectURL);
                    return false;
                }
            }
            Cookie userCookie = new Cookie("openId", openId);
            //存活期1天
            userCookie.setMaxAge(60 * 60 * 24);
            userCookie.setPath("/");
            response.addCookie(userCookie);
            return true;
        } else {
            boolean checkCookies = false;
            String token = BusinessUtil.getCookieToken(request, "token");
            if (StringUtils.isNotEmpty(token)) {
                UserBean userBean = (UserBean) redisService.get("LOGIN:" + token);
                if (userBean != null && null != userBean.getId()) {
                    checkCookies = true;
                }
            }
            if (!checkCookies) {
                response.sendRedirect(request.getContextPath() + "/admin/login");
                return false;
            } else {
                //刷新
                Cookie userCookie = new Cookie("token", token);
                //存活期60分钟
                userCookie.setMaxAge(60 * 60 * 24);
                userCookie.setPath("/");
                response.addCookie(userCookie);

                redisService.expire("LOGIN:" + token, 60 * 60L);
                return true;
            }
        }
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
                           ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
            throws Exception {

    }

}